/* 购物车管理 */
class CartManager {
    constructor() {
        this.items = [];
        this.selectedItems = new Set();
        this.init();
    }

    init() {
        this.loadCartFromStorage();
        this.bindEvents();
        this.updateCartCount();
    }

    bindEvents() {
        // 绑定添加到购物车按钮事件
        document.addEventListener('click', (e) => {
            if (e.target.classList.contains('add-to-cart-btn')) {
                const productCard = e.target.closest('.product-card');
                const productId = productCard.dataset.productId;
                const productName = productCard.querySelector('.product-name').textContent;
                const productPrice = parseFloat(productCard.querySelector('.product-price').textContent.replace('¥', ''));
                
                this.addToCart(productId, productName, productPrice);
            }
        });

        // 绑定购物车图标点击事件
        const cartIcon = document.getElementById('cartIcon');
        if (cartIcon) {
            cartIcon.addEventListener('click', (e) => {
                if (!window.authManager || !window.authManager.isAuthenticated || !window.authManager.isAuthenticated()) {
                    e.preventDefault();
                    if (window.authManager && window.authManager.showAuthModal) {
                        window.authManager.showAuthModal('login');
                    }
                    return;
                }
            });
        }
    }

    // 添加到购物车
    async addToCart(productId, productName, price, quantity = 1) {
        if (!window.authManager || !window.authManager.isAuthenticated || !window.authManager.isAuthenticated()) {
            if (window.authManager && window.authManager.showAuthModal) {
                window.authManager.showAuthModal('login');
            }
            return;
        }

        try {
            // 检查商品是否已在购物车中
            const existingItem = this.items.find(item => item.product_id === productId);
            
            if (existingItem) {
                existingItem.quantity += quantity;
            } else {
                this.items.push({
                    product_id: productId,
                    product_name: productName,
                    price: price,
                    quantity: quantity,
                    selected: false
                });
            }

            // 保存到本地存储
            this.saveCartToStorage();
            
            // 更新UI
            this.updateCartCount();
            
            // 显示成功提示
            this.showAddToCartNotification(productName);
            
            // 同步到后端
            try {
                if (window.api && typeof window.api.addToCart === 'function') {
                    const result = await window.api.addToCart(productId, quantity);
                    if (!result.success) {
                        console.warn('同步到后端失败:', result.error);
                    }
                }
            } catch (error) {
                console.warn('同步到后端失败，但已保存到本地:', error);
            }
            
        } catch (error) {
            console.error('添加到购物车失败:', error);
            this.showNotification('添加到购物车失败', 'error');
        }
    }

    // 从购物车移除商品
    async removeFromCart(productId) {
        this.items = this.items.filter(item => item.product_id !== productId);
        this.selectedItems.delete(productId);
        this.saveCartToStorage();
        this.updateCartCount();
        
        // 同步到后端
        try {
            if (window.api && typeof window.api.removeFromCart === 'function') {
                const result = await window.api.removeFromCart(productId);
                if (!result.success) {
                    console.warn('同步到后端失败:', result.error);
                }
            }
        } catch (error) {
            console.warn('同步到后端失败:', error);
        }
    }

    // 更新商品数量
    async updateQuantity(productId, quantity) {
        const item = this.items.find(item => item.product_id === productId);
        if (item) {
            if (quantity <= 0) {
                await this.removeFromCart(productId);
            } else {
                item.quantity = quantity;
                this.saveCartToStorage();
                this.updateCartCount();
                
                // 同步到后端
                try {
                    if (window.api && typeof window.api.updateCartItem === 'function') {
                        const result = await window.api.updateCartItem(productId, quantity);
                        if (!result.success) {
                            console.warn('同步到后端失败:', result.error);
                        }
                    }
                } catch (error) {
                    console.warn('同步到后端失败:', error);
                }
            }
        }
    }

    // 切换商品选中状态
    toggleSelection(productId) {
        const item = this.items.find(item => item.product_id === productId);
        if (item) {
            item.selected = !item.selected;
            if (item.selected) {
                this.selectedItems.add(productId);
            } else {
                this.selectedItems.delete(productId);
            }
            this.saveCartToStorage();
        }
    }

    // 全选/取消全选
    selectAll() {
        this.items.forEach(item => {
            item.selected = true;
            this.selectedItems.add(item.product_id);
        });
        this.saveCartToStorage();
    }

    deselectAll() {
        this.items.forEach(item => {
            item.selected = false;
        });
        this.selectedItems.clear();
        this.saveCartToStorage();
    }

    // 获取选中的商品
    getSelectedItems() {
        return this.items.filter(item => item.selected);
    }

    // 计算总价
    calculateTotal(selectedOnly = false) {
        const items = selectedOnly ? this.getSelectedItems() : this.items;
        return items.reduce((total, item) => total + (item.price * item.quantity), 0);
    }

    // 获取购物车商品数量
    getItemCount() {
        return this.items.reduce((total, item) => total + item.quantity, 0);
    }

    // 更新购物车数量显示
    updateCartCount() {
        const cartCount = document.getElementById('cartCount');
        const count = this.getItemCount();
        cartCount.textContent = count;
        cartCount.style.display = count > 0 ? 'flex' : 'none';
    }

    // 保存购物车到本地存储
    saveCartToStorage() {
        try {
            // 安全地获取用户信息
            let user = null;
            if (window.authManager && typeof window.authManager.getCurrentUser === 'function') {
                user = window.authManager.getCurrentUser();
            } else {
                // 如果authManager还没加载，直接从localStorage获取用户信息
                const userData = localStorage.getItem('currentUser') || localStorage.getItem('userData');
                if (userData) {
                    try {
                        user = JSON.parse(userData);
                    } catch (e) {
                        console.warn('解析用户数据失败:', e);
                    }
                }
            }
            
            if (user && user.username) {
                const cartKey = `cart_${user.username}`;
                localStorage.setItem(cartKey, JSON.stringify(this.items));
            }
        } catch (error) {
            console.error('保存购物车失败:', error);
        }
    }

    // 从本地存储加载购物车
    loadCartFromStorage() {
        try {
            // 安全地获取用户信息
            let user = null;
            if (window.authManager && typeof window.authManager.getCurrentUser === 'function') {
                user = window.authManager.getCurrentUser();
            } else {
                // 如果authManager还没加载，直接从localStorage获取用户信息
                const userData = localStorage.getItem('currentUser') || localStorage.getItem('userData');
                if (userData) {
                    try {
                        user = JSON.parse(userData);
                    } catch (e) {
                        console.warn('解析用户数据失败:', e);
                    }
                }
            }
            
            if (user && user.username) {
                const cartKey = `cart_${user.username}`;
                const stored = localStorage.getItem(cartKey);
                if (stored) {
                    this.items = JSON.parse(stored);
                    // 恢复选中状态
                    this.selectedItems.clear();
                    this.items.forEach(item => {
                        if (item.selected) {
                            this.selectedItems.add(item.product_id);
                        }
                    });
                }
            }
        } catch (error) {
            console.error('加载购物车数据失败:', error);
            this.items = [];
        }
    }

    // 用户登录后重新加载购物车
    async onUserLogin() {
        // 先尝试从后端加载购物车数据
        try {
            if (window.api && typeof window.api.getCart === 'function') {
                const result = await window.api.getCart();
                if (result.success && result.data.items) {
                    this.items = result.data.items;
                    this.selectedItems.clear();
                    this.items.forEach(item => {
                        if (item.selected) {
                            this.selectedItems.add(item.product_id);
                        }
                    });
                    // 同步到本地存储
                    this.saveCartToStorage();
                } else {
                    // 如果后端没有数据，从本地加载
                    this.loadCartFromStorage();
                }
            } else {
                // 如果API还没加载，从本地加载
                this.loadCartFromStorage();
            }
        } catch (error) {
            console.warn('从后端加载购物车失败，使用本地数据:', error);
            this.loadCartFromStorage();
        }
        this.updateCartCount();
    }

    // 用户登出时清空购物车
    onUserLogout() {
        this.items = [];
        this.selectedItems.clear();
        this.updateCartCount();
    }

    // 显示添加到购物车成功提示
    showAddToCartNotification(productName) {
        const notification = document.createElement('div');
        notification.className = 'cart-notification';
        notification.innerHTML = `
            <div class="cart-notification-content">
                <i class="fas fa-check-circle"></i>
                <span>${productName} 已添加到购物车</span>
            </div>
        `;
        
        // 添加样式
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: #28a745;
            color: white;
            padding: 15px 20px;
            border-radius: 8px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
            z-index: 3000;
            transform: translateX(400px);
            transition: transform 0.3s ease;
        `;
        
        document.body.appendChild(notification);
        
        // 显示动画
        setTimeout(() => {
            notification.style.transform = 'translateX(0)';
        }, 100);
        
        // 自动隐藏
        setTimeout(() => {
            notification.style.transform = 'translateX(400px)';
            setTimeout(() => {
                document.body.removeChild(notification);
            }, 300);
        }, 2000);
    }

    // 显示通知
    showNotification(message, type = 'info') {
        if (window.authManager && window.authManager.showNotification) {
            window.authManager.showNotification(message, type);
        }
    }

    // 获取购物车数据（用于订单创建）
    getCartData() {
        return {
            items: this.items,
            total: this.calculateTotal(),
            selectedTotal: this.calculateTotal(true),
            selectedItems: this.getSelectedItems()
        };
    }

    // 同步购物车到后端
    async syncToBackend() {
        if (!window.authManager.isAuthenticated()) {
            return;
        }

        try {
            const result = await api.getCart();
            if (result.success) {
                // 合并后端数据与本地数据
                const backendItems = result.data.items || [];
                const localItems = this.items;
                
                // 简单的合并策略：以本地数据为准
                // 在实际应用中，可能需要更复杂的合并逻辑
                this.items = localItems;
                this.saveCartToStorage();
                this.updateCartCount();
            }
        } catch (error) {
            console.warn('同步购物车失败:', error);
        }
    }
}

// 延迟初始化购物车管理器，确保所有依赖都已加载
document.addEventListener('DOMContentLoaded', () => {
    // 等待一小段时间确保其他模块已加载
    setTimeout(() => {
        window.cartManager = new CartManager();
    }, 100);
});
